class Snake {
  oldbody = [] //记录蛇运动之前的位置
  direction = 'right' //设置蛇移动的方向默认向右
  constructor(options) {
    this.options = options instanceof Object ? options : {}
    //每一节蛇的宽高
    this.width = this.options.width || 20
    this.height = this.options.height || 20
    //蛇的身体，多个小方框拼起来的
    this.body = [
      { x: 3, y: 2, color: 'pink' },
      { x: 2, y: 2, color: 'yellow' },
      { x: 1, y: 2, color: 'yellow' }
    ]
  }
  render(parent) {
    //渲染蛇
    if (this.oldbody.length !== 0) this.remove(parent)
    var dom = document.createDocumentFragment()
    this.body.forEach(v => {
      let el = document.createElement('div')
      el.style.width = this.width + 'px'
      el.style.height = this.height + 'px'
      el.style.position = 'absolute'
      el.style.left = v.x * this.width + 'px'
      el.style.top = v.y * this.height + 'px'
      el.style.backgroundColor = v.color
      dom.appendChild(el)
      this.oldbody.push(el)
    })
    parent.appendChild(dom)
  }
  run(parent) {
    //蛇运动
    //蛇身子运动就是后一节会到上一节的位置。其实有就是删除最后一项然后添加一次蛇头
    let head = JSON.parse(JSON.stringify(this.body[0]))
    switch (this.direction) {
      case 'right':
        head.x += 1
        break
      case 'left':
        head.x--
        break
      case 'top':
        head.y--
        break
      case 'bottom':
        head.y++
        break
    }
    head.color = 'pink'
    //蛇移动相当于不停的添加蛇头删除蛇尾
    this.body.unshift(head)
    //将原来的蛇头改为蛇身体
    this.body[1].color = 'yellow'
    //每移动一次删除最后一项
    this.body.pop()
    this.render(parent)
  }
  remove(parent) {
    //清除上一次渲染结果
    this.oldbody.forEach(v => {
      parent.removeChild(v)
    })
    this.oldbody = []
  }
}

export default Snake
